package com.youlu.myapplication.scratch;

import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.youlu.myapplication.R;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.fragment.app.Fragment;

/**
 * @author : YOULU  sym
 * date   : 2020/11/29 0029
 * desc   :
 */
public class ScratchFragment extends Fragment {

    private static String TAG = "ScratchFragment";
    private boolean DEBUG = true;

    public static final Path a = new Path();
    public static final List<float[]> b = new LinkedList();
    public List<float[]> s;
    public boolean A = true;

    public ScratchView scratchView;
    public Paint paint;
    public List<Path> paths;
    public Path path;
    private float f825u;
    private List<float[]> q;
    public int r;
    private boolean fake_bar_enable = false;
    private String unique_id;
    private int l;
    private ImageView barUndoView;
    private ImageView barDeleteView;
    private ImageView barRedoView;
    public boolean mFlag = true;
    public LinearLayout linearLayout;
    private float v;
    private float w;
    private float x;
    private float y;
    private float z;
    public int t = 0;
    public List<List<float[]>> o;

    public Pair<Pair<Integer, Integer>, Pair<alm[], Integer>> pathInMemory;

    BothwayScrollView scratchScroll;

    public BothwayScrollView.a B = new BothwayScrollView.a() {
        @Override
        public void a() {
            ScratchFragment.this.invalidate();
        }
    };

    public ScratchView.ScratchCallBack scratchCallBack = new ScratchView.ScratchCallBack() {

        @Override
        public Paint setScratchViewCallBack() {
            return ScratchFragment.this.paint;
        }

        @Override
        public List<Path> getPaths() {
            return ScratchFragment.this.paths;
        }

        @Override
        public Path path() {
            return ScratchFragment.this.path;
        }

        @Override
        public int d() {
            return ScratchFragment.this.r;
        }

        @Override
        public List<Boolean> onDraw() {
            int i;
            LinkedList linkedList = new LinkedList();
            float scrollX = (float) ScratchFragment.this.scratchScroll.getScrollX();
            float scrollY = (float) ScratchFragment.this.scratchScroll.getScrollY();
            if (ScratchFragment.this.A) {
                ScratchFragment.this.A = false;
                if (ScratchFragment.this.pathInMemory != null) {
                    scrollX = (float) ((Integer) ((Pair) ScratchFragment.this.pathInMemory.first).first).intValue();
                    i = ((Integer) ((Pair) ScratchFragment.this.pathInMemory.first).second).intValue();
                } else {
                    scrollX = (float) ScratchFragment.this.scratchScroll.getMeasuredWidth();
                    i = ScratchFragment.this.scratchScroll.getMeasuredHeight();
                }
                scrollY = (float) i;
            }
            float measuredWidth = ((float) ScratchFragment.this.scratchScroll.getMeasuredWidth()) + scrollX;
            float measuredHeight = ((float) ScratchFragment.this.scratchScroll.getMeasuredHeight()) + scrollY;
            for (int i2 = 0; i2 < ScratchFragment.this.paths.size(); i2++) {
                boolean z = true;
                if (i2 >= ScratchFragment.this.s.size() || ((float[]) ScratchFragment.this.s.get(i2)).length < 4) {
                    linkedList.add(true);
                } else {
                    float f = ((float[]) ScratchFragment.this.s.get(i2))[0];
                    float f2 = ((float[]) ScratchFragment.this.s.get(i2))[1];
                    float f3 = ((float[]) ScratchFragment.this.s.get(i2))[2];
                    float f4 = ((float[]) ScratchFragment.this.s.get(i2))[3];
                    if (Math.max(scrollX, f) > Math.min(measuredWidth, f3) || Math.max(scrollY, f2) > Math.min(measuredHeight, f4)) {
                        z = false;
                    }
                    linkedList.add(Boolean.valueOf(z));
                }
            }
            return linkedList;
        }
    };


    //通知UI 重绘
    public void invalidate() {
        this.scratchView.invalidate();
    }

    public static Bundle newBundle(String str, boolean z2) {
        Bundle bundle = new Bundle();
        bundle.putString("id.unique", str);
        bundle.putBoolean("fake.bar.enable", z2);
        return bundle;
    }


    public static ScratchFragment createFragment(String str, boolean z2) {
        ScratchFragment scratchFragment = new ScratchFragment();
        scratchFragment.setArguments(newBundle(str, z2));
        return scratchFragment;
    }

    @Override
    public void onActivityCreated(Bundle bundle) {
        super.onActivityCreated(bundle);
        if (getArguments() != null) {
            fake_bar_enable = getArguments().getBoolean("fake.bar.enable");
            unique_id = getArguments().getString("id.unique");
        }
        /*if (getActivity() instanceof Activity) {
            ((FbActivity) getActivity()).a((FbActivity.a) new FbActivity.a() {
                public boolean onBackPressed() {
                    ScratchFragment.this.t();
                    dde.a((Fragment) ScratchFragment.this, alh.a.pop_out_up_down);
                    return true;
                }
            });
        }*/
        init();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = a(getLayoutInflater(), container, savedInstanceState);
        barRedoView = view.findViewById(R.id.bar_redo_view);
        barDeleteView = view.findViewById(R.id.bar_delete_view);
        barUndoView = view.findViewById(R.id.bar_undo_view);
        scratchScroll = view.findViewById(R.id.scroll_scratch);
        return view;
    }

    public View a(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        return layoutInflater.inflate(h(), viewGroup, false);
    }

    private int h() {
        return R.layout.question_scratch_fragment;
    }


    private void init() {
//        this.fakeBar.setVisibility(this.k ? 0 : 8);
        this.pathInMemory = ScratchInnclass.newInstance().memorySearch(unique_id);
        this.scratchScroll.getViewTreeObserver().addOnGlobalLayoutListener((ViewTreeObserver.OnGlobalLayoutListener) this::onGlobalLayout);
        this.l = hv.a(ViewConfiguration.get(getActivity())) / 4;
        this.paint = new Paint();
        this.paint.setAntiAlias(true);
        this.paint.setDither(true);
        this.paint.setColor(getResources().getColor(R.color.bg_scratch));
        this.paint.setStyle(Paint.Style.STROKE);
        this.paint.setStrokeCap(Paint.Cap.ROUND);
        this.paint.setStrokeJoin(Paint.Join.ROUND);
        this.paint.setStrokeWidth(4.0f);
        k();
    }

    public void delete() {
        if (this.r < this.paths.size()) {
            this.paths.set(this.r, a);
            this.o.set(this.r, b);
            this.s.set(this.r, new float[0]);
            this.r++;
            this.paths = this.paths.subList(0, this.r);
            this.o = this.o.subList(0, this.r);
            this.s = this.s.subList(0, this.r);
        } else if (this.r == this.paths.size()) {
            this.paths.add(a);
            this.o.add(b);
            this.s.add(new float[0]);
            this.r++;
        } else {
            this.paths.add(a);
            this.o.add(b);
            this.s.add(new float[0]);
            this.r = this.paths.size();
        }
        invalidate();
        a(this.paths.size(), this.r, n());
    }


    public void redo() {
        if (this.r < paths.size()) {
            r++;
            a(this.paths.size(), this.r, n());
            invalidate();
        }
    }


    public void undo() {
        int i2 = this.r;
        if (i2 > 0) {
            r = i2 - 1;
            a(paths.size(), r, n());
            invalidate();
        }
    }


    public void v() {
        alm[] almArr;
        float f2 = 0;
        float f3 = 0;
        float f4 = 0;
        alm[] almArr2;
        int i2;
        Pair<Pair<Integer, Integer>, Pair<alm[], Integer>> pair = this.pathInMemory;
        //此处有删除
        if (!(pair == null || pair.second == null)) {
            alm[] almArr3 = (alm[]) ((Pair) this.pathInMemory.second).first;
            int length = almArr3.length;
            int i3 = 0;
            while (true) {
                int i4 = 1;
                if (i3 >= length) {
                    break;
                }
                alm alm = almArr3[i3];
                Path path = new Path();
                List linkedList = new LinkedList();
                float f5 = -1.0f;
                if (alm.a() == null) {
                    path = a;
                    linkedList = b;
                    almArr = almArr3;
                    f4 = -1.0f;
                    f3 = -1.0f;
                    f2 = -1.0f;
                } else {
                    float[] a2 = alm.a();
                    float[] b2 = alm.b();
                    if (a2.length != b2.length) {
                        almArr = almArr3;
                        i3++;
                        almArr3 = almArr;
                    } else {
                        int i5 = 0;
                        float f6 = -1.0f;
                        f4 = -1.0f;
                        f3 = -1.0f;
                        f2 = -1.0f;
                        while (i5 < a2.length) {
                            if (i5 == 0) {
                                path.moveTo(a2[i5], b2[i5]);
                                almArr2 = almArr3;
                                f3 = a2[i5];
                                f4 = b2[i5];
                                f2 = f4;
                                i2 = 2;
                                f6 = f3;
                            } else {
                                if (i5 == a2.length - i4) {
                                    path.lineTo(a2[i5], b2[i5]);
                                    almArr2 = almArr3;
                                } else {
                                    int i6 = i5 - 1;
                                    almArr2 = almArr3;
                                    path.quadTo(a2[i6], b2[i6], (a2[i6] + a2[i5]) / 2.0f, (b2[i6] + b2[i5]) / 2.0f);
                                }
                                float min = Math.min(f6, a2[i5]);
                                f6 = min;
                                f4 = Math.min(f4, b2[i5]);
                                f3 = Math.max(f3, a2[i5]);
                                f2 = Math.max(f2, b2[i5]);
                                i2 = 2;
                            }
                            float[] fArr = new float[i2];
                            fArr[0] = a2[i5];
                            fArr[1] = b2[i5];
                            linkedList.add(fArr);
                            i5++;
                            almArr3 = almArr2;
                            i4 = 1;
                        }
                        almArr = almArr3;
                        f5 = f6;
                    }
                }
                this.paths.add(path);
                this.o.add(linkedList);
                this.s.add(new float[]{f5, f4, f3, f2});
                this.r++;
                i3++;
                almArr3 = almArr;
            }
            this.r = ((Integer) ((Pair) this.pathInMemory.second).second).intValue();
            final int intValue = ((Integer) ((Pair) this.pathInMemory.first).first).intValue();
            final int intValue2 = ((Integer) ((Pair) this.pathInMemory.first).second).intValue();
            this.A = true;
            this.scratchScroll.postDelayed(() -> ScratchFragment.this.scratchScroll.scrollTo(intValue, intValue2), 300);
        }
        a(this.paths.size(), this.r, n());
    }


    static int a(ScratchFragment arg0, int arg1) {
        arg0.t = arg1;
        return arg1;
    }


    public void b(float f2, float f3) {
        float abs = Math.abs(f2 - this.f825u);
        float abs2 = Math.abs(f3 - this.v);
        int i2 = this.l;
        if (abs < ((float) i2) && abs2 < ((float) i2)) {
            return;
        }
        if (this.path == null || a((Collection<?>) this.q)) {
            a(f2, f3);
            return;
        }
        Path path = this.path;
        float f4 = this.f825u;
        float f5 = this.v;
        path.quadTo(f4, f5, (f2 + f4) / 2.0f, (f3 + f5) / 2.0f);
        this.q.add(new float[]{(this.f825u + f2) / 2.0f, (this.v + f3) / 2.0f});
        this.f825u = f2;
        this.v = f3;
        this.w = Math.min(this.w, (this.f825u + f2) / 2.0f);
        this.x = Math.min(this.x, (this.v + f3) / 2.0f);
        this.y = Math.max(this.y, (f2 + this.f825u) / 2.0f);
        this.z = Math.max(this.z, (f3 + this.v) / 2.0f);
    }

    public static boolean a(Collection<?> collection) {
        return collection == null || collection.size() == 0;
    }

    public void a(float f2, float f3) {
        this.path = new Path();
        this.q = new LinkedList();
        this.path.moveTo(f2, f3);
        this.q.add(new float[]{f2, f3});
        this.f825u = f2;
        this.v = f3;
        this.w = f2;
        this.y = f2;
        this.x = f3;
        this.z = f3;
    }

    public void m() {
        Path path = this.path;
        if (path != null && this.q != null) {
            path.lineTo(this.f825u, this.v);
            this.q.add(new float[]{this.f825u, this.v});
            if (this.q.size() < 3) {
                o();
                return;
            }
            if (this.r < this.paths.size()) {
                this.paths.set(this.r, this.path);
                this.o.set(this.r, this.q);
                this.s.set(this.r, new float[]{this.w, this.x, this.y, this.z});
                this.r++;
                this.paths = this.paths.subList(0, this.r);
                this.o = this.o.subList(0, this.r);
                this.s = this.s.subList(0, this.r);
            } else if (this.r == this.paths.size()) {
                this.paths.add(this.path);
                this.o.add(this.q);
                this.s.add(new float[]{this.w, this.x, this.y, this.z});
                this.r++;
            } else {
                this.paths.add(this.path);
                this.o.add(this.q);
                this.s.add(new float[]{this.w, this.x, this.y, this.z});
                this.r = this.paths.size();
            }
            a(this.paths.size(), this.r, n());
            o();
        }
    }

    private void a(int i2, int i3, boolean z2) {
        boolean z3 = true;
        this.barDeleteView.setEnabled(i3 > 0 && !z2);
        this.barUndoView.setEnabled(i3 > 0);
        ImageView imageView = this.barRedoView;
        if (i3 >= i2) {
            z3 = false;
        }
        imageView.setEnabled(z3);
    }


    public void o() {
        this.path = null;
        this.q = null;
    }

    private boolean n() {
        int i2 = this.r;
        if (i2 != 0 && this.paths.get(i2 - 1) == a) {
            return true;
        }
        return false;
    }


    private void k() {
//        this.fakeBar.setBackgroundResource(alh.b.scratch_bar_bg);
//        this.scratchActionBar.setBackgroundResource(alh.b.scratch_bar_bg);
        ImageView imageView = this.barUndoView;
        imageView.setImageResource(imageView.isEnabled() ? R.mipmap.scratch_bar_undo : R.mipmap.scratch_bar_undo_disable);
        ImageView imageView2 = this.barDeleteView;
        imageView2.setImageResource(imageView2.isEnabled() ? R.mipmap.scratch_bar_delete : R.mipmap.scratch_bar_delete_disable);
        ImageView imageView3 = this.barRedoView;
        imageView3.setImageResource(imageView3.isEnabled() ? R.mipmap.scratch_bar_redo : R.mipmap.scratch_bar_redo_disable);
    }


    private void onGlobalLayout() {

        if (mFlag) {
            mFlag = false;
            final int measuredWidth = scratchScroll.getMeasuredWidth();
            final int measuredHeight = scratchScroll.getMeasuredHeight();
            if (DEBUG) {
                Log.i(TAG, "measuredWidth : " + measuredWidth + " measuredHeight : " + measuredHeight);
            }
            linearLayout = new LinearLayout(ScratchFragment.this.getActivity());
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            scratchView = new ScratchView(ScratchFragment.this.getActivity());
            scratchView.setLayoutParams(new LinearLayout.LayoutParams(measuredWidth * 5, measuredHeight * 5));

            linearLayout.addView(scratchView);
            scratchScroll.addView(linearLayout, layoutParams);
            if (pathInMemory == null || !(pathInMemory == null || pathInMemory.second == null || ((Pair) pathInMemory.second).first == null || ((alm[]) ((Pair) ScratchFragment.this.pathInMemory.second).first).length != 0)) {
                ScratchFragment.this.scratchScroll.postDelayed(() -> ScratchFragment.this.scratchScroll.a(measuredWidth, measuredHeight), 300);
            }
            linearLayout.setOnTouchListener((view, motionEvent) -> {
                float x = motionEvent.getX();
                float y = motionEvent.getY();
                scratchScroll.requestDisallowInterceptTouchEvent(true);
                int action = motionEvent.getAction() & MotionEvent.ACTION_MASK;
                Log.i(TAG, "action ==== " + action);
                if (action == MotionEvent.ACTION_DOWN) {
                    t = 1;
                    a(x, y);
                    invalidate();
                } else if (action == MotionEvent.ACTION_UP) {
                    if (t == 1) {
                        m();
                        invalidate();
                    }
                    t = t - 1;
                } else if (action == MotionEvent.ACTION_MOVE) {
                    if (t == 1) {
                        b(x, y);
                        invalidate();
                        return true;
                    } else if (t == 2) {
                        scratchScroll.requestDisallowInterceptTouchEvent(false);
                        return false;
                    }

                } else {
                    if (action == MotionEvent.ACTION_POINTER_DOWN) {
                        o();
                        t = t + 1;
                    } else if (action == MotionEvent.ACTION_POINTER_UP) {
                        t = t - 1;
                    }
                }
                return true;
            });

            //设置 按钮的点击事件
            barRedoView.setOnClickListener(v -> ScratchFragment.this.redo());

            barUndoView.setOnClickListener(v -> ScratchFragment.this.undo());

            barDeleteView.setOnClickListener(v -> ScratchFragment.this.delete());


            ScratchFragment.this.B.a(scratchScroll);
            ScratchFragment.this.scratchCallBack.setScratchViewCallBack(scratchView);
            ScratchFragment.this.linearLayout.setBackgroundResource(R.color.bg_scratch);

            ScratchFragment.this.paths = new ArrayList();
            ScratchFragment.this.o = new LinkedList();
            ScratchFragment.this.s = new LinkedList();

            ScratchFragment.this.v();
        }
    }


    public static class ScratchInnclass {
        private static ScratchInnclass instance;

        private ScratchInnclass() {
        }

        public static ScratchInnclass newInstance() {
            if (instance == null) {
                synchronized (ScratchInnclass.class) {
                    if (instance == null) {
                        instance = new ScratchInnclass();
                    }
                }
            }
            return instance;
        }

        public Pair<Pair<Integer, Integer>, Pair<alm[], Integer>> memorySearch(String str) {
            ScratchData scratchData = (ScratchData) ddl.a("business_question", format(str), (Type) ScratchData.class);
            if (scratchData == null) {
                return null;
            }
            return new Pair<>(new Pair(scratchData.scratchScrollX, scratchData.scratchScrollY), new Pair(scratchData.paths, scratchData.nextStroke));
        }

        public boolean save(String str, int i, int i2, alm[] almArr, int i3) {
            ddl.a("business_question", format(str), (Object) new ScratchData(i, i2, almArr, i3));
            return true;
        }

        public boolean save(String str) {
            ddl.a("business_question", format(str));
            return true;
        }

        private static final String format(String str) {
            return String.format("scratch_data_%s", str);
        }
    }


    static class ScratchData extends BaseData {
        int nextStroke;
        alm[] paths;
        int scratchScrollX;
        int scratchScrollY;

        public ScratchData(int i, int i2, alm[] almArr, int i3) {
            this.scratchScrollX = i;
            this.scratchScrollY = i2;
            this.paths = almArr;
            this.nextStroke = i3;
        }
    }
}
